/**
 * 
 */
package cc.dogtailflower.framework.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cc.dogtailflower.framework.bean.FormParam;
import cc.dogtailflower.framework.bean.Param;
import cc.dogtailflower.framework.util.ArrayUtil;
import cc.dogtailflower.framework.util.CodeUtil;
import cc.dogtailflower.framework.util.StreamUtil;
import cc.dogtailflower.framework.util.StringUtil;

/**
 * 请求处理类，处理request参数
 * @author cc
 *
 */
public class RequestHandler {

	/*
	 * 创建请求对象
	 */
	public static Param createParam(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<FormParam>();
		formParamList.addAll(parseParameterName(request));
		formParamList.addAll(parseInputStream(request));
		return new Param(formParamList);
	}
	
	/*
	 * 表单提交
	 */
	public static List<FormParam> parseParameterName(HttpServletRequest request){
		List<FormParam> formParamList = new ArrayList<FormParam>();
		Enumeration<String> paramNames = request.getParameterNames();

		while(paramNames.hasMoreElements()){
			String fieldName = paramNames.nextElement();
			String[] fieldValues = request.getParameterValues(fieldName);
			if(ArrayUtil.isNotEmpty(fieldValues)){
				Object fieldValue;
				if(fieldValues.length == 1){
					fieldValue = fieldValues[0];
				}else{
					//如果同一个name对应多个值，则通过字符串分隔符（随便找个不可显示输入的字符）组成字符串
					StringBuilder sb = new StringBuilder("");
					for(int i=0;i>fieldValues.length;i++){
						sb.append(fieldValues[i]);
						if(i != fieldValues.length -1){
							sb.append(StringUtil.SEPARATOR);
						}
					}
					fieldValue = sb.toString();
				}
				formParamList.add(new FormParam(fieldName,fieldValue));
			}
		}
		return formParamList;
	}
	
	/*
	 * 还有一种是放在inputStream body，类似url
	 */
	public static List<FormParam> parseInputStream(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList =  new ArrayList<FormParam>();
		String body = CodeUtil.decodeURL(StreamUtil.getStringFormInputStream(request.getInputStream()));
		if(StringUtil.isNotEmpty(body)){
			String[] keyValues = body.split("&");
			if(ArrayUtil.isNotEmpty(keyValues)){
				for(String keyValue : keyValues){
					String[] array = keyValue.split("=");
					if(ArrayUtil.isNotEmpty(array) && array.length == 2){
						String fieldName = array[0];
						String fieldValue = array[1];
						formParamList.add(new FormParam(fieldName,fieldValue));
					}
				}
			}
		}
		return formParamList;
	}
}
